class Dog:
    def __init__(self, name):
        self.name = name

    def eat(self, food):
        print(f"eat {food}...")

    def sleep(self):
        print("sleep...")


def talk(num):
    print(f"talk {num}...")


d = Dog("二狗")

# hasattr、getattr的使用
# choice = input("输入要执行的方法/属性：")
# if hasattr(d, choice):
#     try:
#         func = getattr(d, choice)
#         func("ddd")  # 调用
#     except TypeError:
#         print(getattr(d, choice))
# getattr(d, "sleep")()  # 调用

# # 动态添加属性
# attr = input("属性名：")
# value = input("属性值：")
# if value.isdigit():
#     setattr(d, attr, int(value))
# else:
#     setattr(d, attr, value)
# print(dir(d))
# print(getattr(d, attr))
# print(type(getattr(d, attr)))

# 动态添加方法
setattr(d, "talk", talk)
d.talk(4)

# 动态删除
delattr(d, "talk")

# getattr(d, "talk")()

x = 10


def func():
    y = 20
    a = eval("x+y")
    print(f"x: {x}, y: {y}")
    print(f"a: {a}")

    b = eval("x+y", {"x": 1, "y": 2})
    print(f"x: {x}, y: {y}")
    print(f"b: {b}")

    # eval(expression, globals=None, locals=None)  # 构建的时候 设置当前eval内的 全局变量，本地变量 如果本地有变量，就是用本地的，没有就用全局的
    c = eval("x+y", {"x": 1, "y": 2}, {"x": 3, "y": 4})
    print(f"x: {x}, y: {y}")
    print(f"c: {c}")


func()


a = eval("'张三'")  # 正确的，相当于 a = '张三' 字符串赋值给a
# a = eval("张三")  # 会报错，这里的写法相当于直接写 a = 张三  张三没有被定义
print(a)  # 张三

xx = 1
yy = exec("xx = 1 + 1")  # 这里会改变全局的xx  exec没有返回值
print(xx)  # 2
print(yy)  # None

# 支持更复杂的逻辑
exec("a = []\na.append(1)\na.append(2)\na.append(3)")  # 注意， \n后 要紧跟着写别的东西 不然就会识别错误
print(a)  # [1, 2, 3]

bb = "mydict = {'name': '张三', 'age': 18}"
print(type(bb))  # <class 'str'>
exec(bb)
print(mydict)  # {'name': '张三', 'age': 18}
print(type(mydict))  # <class 'dict'>
